﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Data;
using Aden.Util.Common;
using Aden.Util.Database;
using Aden.Model.AppProcess;

namespace Aden.DAL.AppProcess
{
    public class AppProcessFactory
    {
        /* 返回值：时间数组（StartTime，EndTime）
         * 1 null：不能修改
         * 2 StartTime = null： 时间< EndTime时且上程序Submitted后，才能修改
         * 3 StartTime和EndTime都有值： 
         *      a < StartTime时必须上程序Submitted后，才能修改；
         *      b 【StartTime，EndTime】时，只要本程序没有Submitted，可以修改
         *      c > EndTime时，只读
         */
        public Dictionary<string,object> GetPeriod(string appGuid, string costCenterCode, DateTime? odate=null)
        {
            try
            {
                DateTime orderDate = odate?? DateTime.Now;

                string sql = "select top 1 isnull(A1.StartTimeToChange, '0:0') StartTimeToChangeOfThis, " +
                    " isnull(a1.EndTimeToChange, '23:59:59') endTimeToChangeOfThis, a1.DaysToChange DaysToChangeOfThis, " +
                    " isnull(A4.LastAppGroup,'') LastAppGroup,isnull(A4.FirstAppGroup,'') FirstAppGroup," +
                    "isnull(A4.AppGroup,'') AppGroup,A3.StartTimeToChange StartTimeToChangeOfLast, " +
                    " A3.EndTimeToChange EndTimeToChangeOfLast, A3.DaysToChange DaysToChangeOfLast " +
                    " from tblAppProcess (nolock) A1 JOIN tblApps (nolock) A4 ON A1.APPGUID = A4.GUID " +
                    " JOIN [dbo].[DM_D_ERP_COSTCENTER] (NOLOCK) A2 ON A1.Company = A2.Division " +
                    " left join (select isnull(A31.StartTimeToChange,'0:0') StartTimeToChange, " +
                    " isnull(A31.EndTimeToChange,'23:59:59') endTimeToChange,A31.DaysToChange, A32.appGroup, " +
                    " dateadd (d,-a31.DaysToChange,cast('{2}' + ' '+ isnull(A31.endTimeToChange,'0:0') as datetime)) endDateTimeToChangeOfLast " +
                    " from tblAppProcess (nolock) A31, tblApps (nolock) A32 where A31.appGuid = a32.guid and " +
                    " GETDATE() between isnull(A31.StartDate, '2000-01-01') and isnull(A31.EndDate, '2222-12-31')) A3 " +
                    " on A4.LastAppGroup = A3.appGroup where A1.appGuid ='{0}' and A2.costCenterCode = '{1}' " +
                    " and getdate() between isnull(A1.StartDate, '2000-01-01') and isnull(A1.EndDate, '2222-12-31') " +
                    " order by DATEDIFF(s,isnull(a3.endDateTimeToChangeOfLast, GETDATE()), dateadd(d, -a1.DaysToChange, " +
                    " cast('{2}' + ' ' + isnull(A1.StartTimeToChange, '0:0') as datetime))) ; ";

                sql = string.Format(sql, appGuid, costCenterCode, orderDate.ToString("yyyy-MM-dd"));

                DataTable dt = SqlServerHelper.GetDataTable(SqlServerHelper.salesorderConn(), sql);
                if (dt == null || !dt.AsEnumerable().Any()) return null;
                
                DataRow row = dt.Rows[0];
                
                DateTime date = orderDate.AddDays(-1 * row["daysToChangeOfThis"].ToInt());
                DateTime startDateTimeToChangeOfThis = DateTime.Parse(string.Join(" ",
                    date.ToString("yyyy-MM-dd"), row["startTimeToChangeOfThis"].ToStringTrim()));
                DateTime endDateTimeToChangeOfThis = DateTime.Parse(string.Join(" ",
                    date.ToString("yyyy-MM-dd"), row["endTimeToChangeOfThis"].ToStringTrim()));

                Dictionary<string, object> dic = new Dictionary<string, object>();
                dic.Add("StartTime", startDateTimeToChangeOfThis);
                dic.Add("EndTime", endDateTimeToChangeOfThis);
                dic.Add("LastApp", row["LastAppGroup"].ToStringTrim());
                dic.Add("FirstApp", row["FirstAppGroup"].ToStringTrim());
                dic.Add("ThisApp", row["AppGroup"].ToStringTrim());
                dic.Add("DaysToChangeOfThis", row["DaysToChangeOfThis"].ToStringTrim());

                //没有上一程序
                if (string.IsNullOrWhiteSpace(row["startTimeToChangeOfLast"].ToStringTrim()))
                {
                    return dic;
                }
                
                date = orderDate.AddDays(-1 * row["daysToChangeOfLast"].ToInt());
                DateTime startDateTimeToChangeOfLast = DateTime.Parse(string.Join(" ",
                    date.ToString("yyyy-MM-dd"), row["startTimeToChangeOfLast"].ToStringTrim()));
                DateTime endDateTimeToChangeOfLast = DateTime.Parse(string.Join(" ",
                    date.ToString("yyyy-MM-dd"), row["endTimeToChangeOfLast"].ToStringTrim()));

                if (DateTime.Parse("0:0").TimeOfDay.Equals(endDateTimeToChangeOfLast)           //上程序的deadline为零点
                    || startDateTimeToChangeOfThis >= endDateTimeToChangeOfLast)
                {   //无交叉
                    return dic;
                }
                if (endDateTimeToChangeOfThis < startDateTimeToChangeOfLast)  //本程序的时间段在前
                    return null;

                if (endDateTimeToChangeOfThis > endDateTimeToChangeOfLast)
                {
                    dic["StartTime"] = endDateTimeToChangeOfLast;
                    return dic;
                }

                dic.Remove("StartTime");
                return dic;
            }
            catch(Exception ex)
            {
                throw ex;
            }
        }

        public DateTime GetEndTime (string appGuid, string costCenterCode, DateTime? odate = null)
        {
            // PO 截单时间
            DateTime endTime = (DateTime)new AppProcessFactory().GetPeriod(appGuid, costCenterCode, odate)["EndTime"];

            return endTime;
        }
    }
}